#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8
# vim:tabstop=4
#
# Copyright (c) 2010 by xkhhdx
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
__serviceprovider__ = "renren"

__properties__ = {
    "username" : u"帐号",
    "password" : u"密码",
}

__api__ = "" # 无所谓

__lengthlimit__ = 140

import base64, re

import _pub_renren

def update(properties, msg):

    try:
        result = _pub_renren.rr_sync(properties, msg)
        if False:
            # 此段代码部署到 GAE 会出错 本地没有关系
            # 原因是 urllib2 中含有关于 socket 的操作被 GAE 限制了
            # 解决方案是采用 urlfetch 不过要自己维持 cookie 和 重定向…… -_-#...
            import urllib, urllib2, cookielib
            username = properties["username"]
            password = properties["password"]
            cookie=cookielib.CookieJar()
            opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
            urllib2.install_opener(opener)
            str=urllib.urlencode({'email':  username,'password': password})
            login_response=urllib2.urlopen('http://www.renren.com/PLogin.do',str)
            logging.info(login_response.read())
            status_url = 'http://status.renren.com/'
            login_response=urllib2.urlopen(status_url)
            page = login_response.read()
            ticket = re.search('<input type="hidden" value="(-?\d+)" class="submit" id="publisher_form_ticket"/>', page)
            status_url = 'http://status.renren.com/doing/update.do?'
            str=urllib.urlencode({'c': msg,'raw': msg,'statusPage': 1,'publisher_form_ticket': ticket.group(1),})
            login_response=urllib2.urlopen(status_url,str)

            result = login_response.read()


    except Exception,e:
        return True, e
    else:

        if result.find("<status/>") < 0:
            return False, "succeed!"
        else:
            return True, "Failed!"

if __name__ == "__main__":
    properties = __properties__

    properties["username"] = ""
    properties["password"] = ""

    s,r = update(properties, u"hello world你好")
    print "s,r=", s, r
